package servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import utils.JDBCConnector;
import utils.MDGenerator;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Servlet implementation class RegisterServlet
 */
public class RegisterServlet extends HttpServlet {

  private static final long serialVersionUID = -1485882677997956764L;

  @Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    
    String name = request.getParameter("name");
    String password = request.getParameter("password");
    String email = request.getParameter("email");
    
    try(Connection c = JDBCConnector.getConnection()){
      PreparedStatement pstmt = c.prepareStatement("insert into user_info values(?,?,?,?)");
      pstmt.setString(1, name.charAt(0) + String.valueOf(System.currentTimeMillis()));
      pstmt.setString(2, name);
      pstmt.setString(3, MDGenerator.md5(password)); // 加密
      pstmt.setString(4, email);
      pstmt.executeUpdate();
    } catch (SQLException e) {
      System.out.println(e.getMessage());
      response.getWriter().println("注册失败<hr />");
      request.getRequestDispatcher("/login.html").include(request, response);
    }
    response.getWriter().println("注册成功<hr />");
    request.getRequestDispatcher("/login.html").include(request, response);
	}

}
